<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 商品管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>
                <el-button
                        type="primary"
                        icon="el-icon-plus"
                        class="handle-del mr10"
                        @click="handleAdd"
                >添加</el-button>
            </div>
            <el-table
                :data="showTabData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="productId" label="ID" width="85" align="center">
                  <template slot-scope="scope">{{ getCurrentIDX(scope.$index + 1)}}</template>
                </el-table-column>
                <el-table-column prop="intro" label="产品类型" width="85">
                  <template slot-scope="scope">
                    <span v-html="getCategory(scope.row.cid)"></span>
                  </template>
                </el-table-column>
                <el-table-column prop="intro" label="产品名称" width="270">
					<template slot-scope="scope">
						<span v-html="scope.row.intro"></span>
					</template>
				</el-table-column>
                <el-table-column prop="price" label="产品原价">
                    <template slot-scope="scope">{{scope.row.price}}</template>
                </el-table-column>
                <el-table-column prop="promotePrice" label="优惠价格">
                    <template slot-scope="scope">{{scope.row.promotePrice}}</template>
                </el-table-column>
                <el-table-column prop="imgUrl" label="封面图片" align="center">
                    <template slot-scope="scope">
                       <el-image
                           class="table-td-thumb"
                           :src="scope.row.imgUrl[0]"
						   width="50" height="50"
                           :preview-src-list="[scope.row.imgUrl[0]]"
                       ></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="shopName" label="店铺名称" width="120">
                    <template slot-scope="scope">
						<span v-html="scope.row.shopName"></span>
					</template>
                </el-table-column>
                <el-table-column prop="userName" label="产品销量">
                    <template slot-scope="scope">{{scope.row.saleNum}}</template>
                </el-table-column>
                <el-table-column prop="collectNum" label="评论数量">
                    <template slot-scope="scope">{{scope.row.collectNum}}</template>
                </el-table-column>
                <el-table-column prop="email" label="库存数量">
                    <template slot-scope="scope">{{scope.row.stock}}</template>
                </el-table-column>
                <el-table-column label="操作" width="90" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row.productId)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

<!--        添加弹框-->
        <el-dialog title="添加" :visible.sync="addVisible" width="45%" class='dialog-form'>
            <el-form ref="form" :model="addForm" label-width="80px" label-position='left' :rules='rules'>
              <el-row type="flex" class="row-bg" justify="center">
                <el-col :span="11">
                  <div class="grid-content bg-purple">
                    <el-form-item label="产品名称" prop='intro' class='itemRequired'>
                      <el-input v-model="addForm.intro"></el-input>
                    </el-form-item>
                    <el-form-item label="产品原价" class='itemRequired'>
                      <el-input-number size="medium" v-model="addForm.price" :min="1"></el-input-number>
                    </el-form-item>
                    <el-form-item label="优惠价格" class='itemRequired'>
                      <el-input-number size="medium" v-model="addForm.promotePrice" :min="1"></el-input-number>
                    </el-form-item>

                    <el-form-item label="封面图片" class='itemRequired'>
                      <el-upload
                        class="avatar-uploader"
                        :action='qiniuAction'
                        :show-file-list="false"
                        :data='qiniuData'
                        :on-change="imgSaveToUrl"
                        :before-upload="beforeAvatarUpload"
                        :on-success="updateSuccess"
                        :on-error="updateError"
                      >
                        <img v-if="addForm.imgUrl[0]" :src="addForm.imgUrl[0]" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                    </el-form-item>
                  </div>
                </el-col>
                <el-col :span="11"  :offset='1'>
                  <div class="grid-content bg-purple">
                    <el-form-item label="产品类别" class='itemRequired'>
                      <el-select v-model="addForm.cid">
                        <el-option v-for="item in categoryOption" :key="item.key" :label="item.value" :value="item.key">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="店铺名称" prop='shopName' class='itemRequired'>
                        <el-input v-model="addForm.shopName"></el-input>
                    </el-form-item>
                    <el-form-item label="产品销量" class='itemRequired'>
                      <el-input-number size="medium" v-model="addForm.saleNum" :min="1"></el-input-number>
                    </el-form-item>
                    <el-form-item label="评论数量" class='itemRequired'>
                      <el-input-number size="medium" v-model="addForm.collectNum" :min="1"></el-input-number>
                    </el-form-item>
                    <el-form-item label="库存数量" class='itemRequired'>
                      <el-input-number size="medium" v-model="addForm.stock" :min="1"></el-input-number>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'

// 产品名称
const userNameValidate = (rule, value, callback) => {
  const reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s\-]{2,10}$/
  if (value === undefined || value === '') {
    callback(new Error('产品名称不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入2-10个汉字！'))
  } else {
    callback()
  }
}
// 店铺名称
const shopNameValidate = (rule, value, callback) => {
  const reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s\-]{2,20}$/
  if (value === undefined || value === '') {
    callback(new Error('店铺名称不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入2-20个汉字！'))
  } else {
    callback()
  }
}

export default {
    name: 'producttable',
    data() {
        return {
            beforeImg: 'http://img14.360buyimg.com/n5/',
            query: {
                address: '',
                name: '',
                pageIndex: 1,
                pageSize: 20
            },
            tableData: [],
            showTabData: [],
			cid: 0,
            multipleSelection: [],
            // 七牛云图片上传
            qiniuAction:"https://upload-z2.qiniup.com",//七牛云上传地址-华南
            qiniuData: {
              token: "",
              key: ''
            },
            qiniu_OutChain: 'http://qwq973aqg.hn-bkt.clouddn.com',//七牛云图片外链地址
            // 添加表单
            addVisible :false,
            pageTotal: 0,
            categoryOption: [],
            addForm: {
              cid: 1,
              imgUrl: ['http://img14.360buyimg.com/n1/jfs/t20839/49/431961706/166160/b6fee35/5b0d0b00N553998e7.jpg'],
              price: 1,
              promotePrice: 1,
              saleNum: 0,
              collectNum: 0,
              stock: 0
            },
            idx: -1,
            id: -1,
            // 表单验证提示
            rules: {
              intro: [{ validator: userNameValidate, trigger: 'blur'}],
              shopName: [{ validator: shopNameValidate, trigger: 'blur'}]
            },
        };
    },
    created() {
        this.getData();
        this.getQiniuToken()
    },
    methods: {
        // 获取每条数据的序号
        getCurrentIDX(index) {
          return (this.query.pageIndex - 1) * this.query.pageSize + index
        },
        // 获取产品分类
        getCategory(id) {
          for (let i = 0; i < this.categoryOption.length; i++) {
            if (id === this.categoryOption[i].key) {
              return this.categoryOption[i].value
            }
          }
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            const _this=this;
            this.$http.get("/product/allinCate")
              .then(res => {
                  if(res.data.code === 200) {
                    for (let i = 0; i < res.data.data.length; i++) {
                      _this.tableData = _this.tableData.concat(res.data.data[i].products);
                      _this.pageTotal += res.data.data[i].products.length;
                      // 类别Option
                      _this.categoryOption[i] = {
                        key: i + 1,
                        value: res.data.data[i].cname
                      }
                    }
                    _this.showTabDataByPage()
                  }
              }).catch(err => {
                _this.$message.error("获取信息失败")
              })
        },
        // 分页展示
        showTabDataByPage() {
          const left = (this.query.pageIndex - 1) * this.query.pageSize
          const right = this.tableData.length - left < 20 ? this.tableData.length - left : 20
          this.showTabData = Object.assign([], this.tableData)
          this.showTabData = this.showTabData.splice(left,right)
        },
        // 分页导航
        handlePageChange(val) {
          this.query.pageIndex = val
          this.showTabDataByPage();
        },

        // 七牛云图片上传
        // 获得token
        getQiniuToken() {
          const _this = this
          this.$http.get('/qiniu/token')
            .then(res => {
              _this.qiniuData.token = res.data.data.token
            })
        },
        // 上传图片之前进行处理
        beforeAvatarUpload(file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            return false
          }
          this.qiniuData.key=`update_pic_${file.name}`
        },
        // 上传成功
        updateSuccess(res) {
          this.addForm.imgUrl[0] = `${this.qiniu_OutChain}/${res.key}`
        },
        // 上传失败
        updateError(err) {
          this.$message.error("上传失败,请重试!")
          return false
        },

        // 重置添加表单
        resetAddForm() {
          this.addForm = {
            cid: 1,
            imgUrl: ['http://img14.360buyimg.com/n1/jfs/t20839/49/431961706/166160/b6fee35/5b0d0b00N553998e7.jpg'],
            price: 1,
            promotePrice: 1,
            saleNum: 0,
            collectNum: 0,
            stock: 0
          }
        },
        // 封面图片
        imgSaveToUrl(file) {
          let URL = window.URL || window.webkitURL;
          this.addForm.imgUrl[0] = URL.createObjectURL(file.raw);
        },
        // 添加操作
        handleAdd() {
          this.resetAddForm()
          // 清除表单验证
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
          this.addVisible = true;
        },
        // 保存添加
        saveAdd() {
          this.$refs.form.validate(valid => {
            if (valid) {
              const _this = this
              this.$http.post("/product/add",this.addForm)
                .then(res => {
                  _this.addVisible = false;
                  _this.$set(_this.tableData, _this.idx, _this.addForm);
                  _this.getData()
                  _this.$message.success(`添加成功`);
                  return true
                })
                .catch(err => {
                  _this.$message.error(`添加失败`)
                  return false
                })
            }
          })
        },

        // 删除操作
        handleDelete(index, id) {
          const _this = this
          // 二次确认删除
          this.$confirm('确定要删除吗？', '提示', {
            type: 'error'
          }).then(() => {
              _this.$http.delete("/product/del/"+id).then(res => {
                _this.tableData.splice(index, 1);
                _this.getData()
                _this.$message.success('删除成功');
                return true
              }).catch(err => {
                _this.$message.error("删除失败")
                return false
              })
            })
        },
        // 多选操作
        handleSelectionChange(val) {
          this.multipleSelection = val;
        },
        delAllSelection() {
          for (let i = 0; i < this.multipleSelection.length; i++) {
            if (i < this.multipleSelection.length - 1) {
              this.$http.delete("/product/del/" + this.multipleSelection[i].productId)
            } else {
              this.$http.delete("/product/del/" + this.multipleSelection[i].productId)
                .then(res => {
                  this.multipleSelection = [];
                  this.$message.success('删除成功');
                  return true
                }).cache(err => {
                  this.$message.error('删除失败')
                  return false
              })
            }
          }
        },

    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.dialog-form>>>div.el-dialog__header {
  border-bottom: 1px solid #cfcfcf;
}
.itemRequired>>>label.el-form-item__label::before {
  content: '* ';
  color: #F56C6C;
  margin-right: 2px;
}
.avatar-uploader>>>div.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}
.avatar-uploader>>>div.el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
